package org.dwell.vertx3.protocol;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Created by JianGuo on 2016/1/13.
 */
public abstract class Serializer {

    public static String pack(Object object) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.writeValueAsString(object);
        }catch (JsonProcessingException e){
            e.printStackTrace();
            throw new RuntimeException("Error parsing POJO.");
        }
    }

    public static Object unpack(String json, Class format) {
        try {
            System.out.println(json);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(json, format);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    public static void main(String[] args) {
        try {
            String json = "{\"header\":{\"action\":\"authenticate\"}}";
            Packet packet = (Packet)Serializer.unpack(json, Packet.class);
            System.out.println(packet);
            System.out.println(packet.getAction());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
